13. Dependency Scope and Type

Dependency Scope and Type

ND079 JPND C3 L2 A10 Dependency Scope V3

Dependency Scope

The **scope **element of a dependency tells Maven when to include that dependency.

  • **Compile: **Default scope. Dependency will be available for all Maven actions.
  • **Test: **Only available when building and running unit tests.
  • **Runtime: **Only available when application runs (not when compiled).
  • **Provided: **Only available during compilation (not when run).
  • **System: ***DEPRECATED. *Specify a local jar file as a dependency.
  • **Import: **Import all dependencies from another pom.

This example tells Maven to only include the JUnit dependency during test phases.

<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>5.7.0</version>
        <scope>test</scope>
    </dependency>
</dependencies>

Dependency Type and Packaging

ND079 JPND C3 L2 A11 Dependency Type And Packaging V3

Dependency Type

The **type **element tells Maven what type of artifact is provided by a dependency. The value for this element should correspond to the type provided by the packaging element in that dependency's pom. Packaging types supported by core Maven implementation:

  • jar: default java archive
  • war: web archive
  • ear: enterprise archive containing one or more war files as well as enterprise java bean (ejb) modules packaged as jars
  • rar: resource adapter - used by enterprise java applications to enable access to foreign systems
  • maven-plugin: package a project to be used as a maven plugin
  • pom: the pom of this project is the primary artifact to produce. Used for parent projects containing multiple modules, as well as projects that you wish to including using 'import' scope dependencies

This example would specify to Maven that the JUnit dependency to be included is a JAR. This is unnecessary, as JAR is the default type, but would be necessary if JUnit came as a different kind of package.

<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>5.7.0</version>
        <scope>test</scope>
        <type>jar</type>
    </dependency>
</dependencies>